home | previous topic | next topic

Objectives

ü Use overloaded methods and constructors.


Resources




Method Overloading


  1. Download Java Methods.zip to your desktop and uncompress it.
  2. Double click on package.bluej (skip this step for the Micro-Teaching)
  3. In the Java Methods folder, right click on PassingArguments.java and select Open with Notepad
  4. In the Java Methods folder, right click on PassingArgumentsWithOverloading.java and select Open with Notepad

How to Unzip and Find My Files


SEE MethodOverloading.java

In the above example the method abs() is called three different times. Each time, the argument being passed is a different datatype. This seems to break the rules of the parameter list. The datatypes of the arguments must match the datatypes of the parameter list. The datatype of the value being returned by each method is also different each time. What’s going on?
Go to the API and look up the Math class. In the methods list, you will see there are actually four different listings for the abs method, each method has a different parameter list.

Method Signature

The method signature is made up of the method name and parameter list. Java has no rule stating that all method names must be unique, but ever method signature does need to be unique. This allows us to do something called method overloading. Method overloading is a group of methods with the same names, but different signatures.

public static void myMethod(int a, float b)

public static void myMethod(float a, int b) signature is different

public static void myMethod(int a, int b) signature is different

public static void myMethod(float a, float b) signature is different

public static int myMethod(int a, float b) signature is the same - not valid overloading


API

The API provides all the information you need about classes and methods that either comes with the Java development kit, or classes and methods that other developers have created.

The API provides:
  • list of method names
  • descriptions of what the methods do
  • parameter list for each method
  • return type for that method (void if no value is being returned)
  • whether the method is static or non-static


Coding Challenge

  • break into groups of two or three
  • open a new blank document in Google Docs
  • copy and paste the text from PassingArguments.java into your new document
  • work together to alter this program so that it uses method overloading